<template>
  <el-dialog
    :before-close="handleClose"
    title="创建新动作类型"
    :visible.sync="dialogVisible"
  >
    <el-form
      ref="ruleForm"
      v-loading="loading"
      label-width="120px"
      :model="ruleForm"
      :rules="rules"
      size="mini"
    >
      <el-form-item label="动作类型名" prop="action_name">
        <el-input
          v-model="ruleForm.action_name"
          placeholder="请输入动作类型名"
          spellcheck="false"
        />
      </el-form-item>
      <el-form-item label="动作类型ID" prop="action_id">
        <el-input
          v-model="ruleForm.action_id"
          placeholder="请输入动作类型ID"
          spellcheck="false"
        />
      </el-form-item>
      <el-form-item label="监控器类型ID" prop="monitor_id">
        <el-select v-model="ruleForm.monitor_id">
          <el-option
            v-for="(item, index) in name_list"
            :key="index"
            :label="item.monitor_name"
            :value="item.monitor_id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submit('ruleForm')">保存</el-button>
        <el-button @click="dialogVisible = false">返回</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import monitor from "@/api/recognize/monitor";
import action from "@/api/recognize/action";
import clearWatch from "@/utils/mixin/clearWatch";
export default {
  name: "NewAction",
  mixins: [clearWatch],
  data() {
    return {
      dialogVisible: false,
      loading: false,
      ruleForm: {
        action_name: "",
        action_id: "",
        monitor_id: ""
      },
      name_list: [],
      rules: {
        action_name: [
          { required: true, message: "请输入动作类型名", trigger: "blur" }
        ],
        action_id: [
          { required: true, message: "请输入动作类型ID", trigger: "blur" }
        ],
        monitor_id: [
          { required: true, message: "请选择监控器类型ID", trigger: "change" }
        ]
      }
    };
  },
  methods: {
    handleClose(done) {
      done();
    },
    async show() {
      this.dialogVisible = !this.dialogVisible;
      this.loading = true;
      await monitor.name_list().then(res => {
        this.name_list = res.data.name_list;
      });
      this.loading = false;
    },

    submit(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          action
            .add({
              ...this.ruleForm
            })
            .then(res => {
              this.$emit("change");
              this.$message.success(res.data.message);
              this.dialogVisible = false;
            });
        } else {
          return false;
        }
      });
    }
  }
};
</script>
